// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html
// A*算法公式 F = G + H
// G = 从起点A，沿着产生的路径，移动到网格上指定方格的移动耗费
// H = 从网格上那个方格移动到终点B的预估移动耗费
var map2dx = require("./map")

cc.Class({
    extends: cc.Component,
    ctor:function(){
        this.zhangaiList = []//障碍的坐标集合
        this.startTarget = map2dx.Point(0,0)//开始的坐标
        this.endTarget = map2dx.Point(2,0)//结束的坐标
        },
    properties: {
        player:cc.Node,
        stonePre:cc.Node,
        endPre:cc.Node //结束点的预制体

    },

    onLoad () {
        const t = this
        var layer = this.node.getComponent(cc.TiledMap).getLayer("块层 1")
        window.layer = layer
        window.titleMap = this.node.getComponent(cc.TiledMap)
        window.player = this.player
        window.map = this
        t.moveToGird(this.startTarget.x,this.startTarget.y)
        t.setEnd(this.endTarget.x,this.endTarget.y)
        t.loadStone()

        var mapSearch = new map2dx.Asearch({w:10,h:10},this.zhangaiList,this.startTarget,this.endTarget)
        t.movePathList(mapSearch.pathList)
        

    },
    /**
     * @description 移动
     * @param {*} pathList 
     */
    movePathList(pathList){
        var index = 0
        const t = this
        var time = setInterval(()=>{
            if(index >= pathList.length){
                clearInterval(time)
            }
            var item = pathList[index]
            t.moveToGird(item.x,item.y)
            index += 1
        },500)
    },

    start () {
    
    }
    ,
    loadMap(){
        console.log("loading map")
    }
    ,
    setEnd(x,y){
        this.endPre.setPosition(window.layer.getPositionAt(x,y))
    }
    ,
    moveToGird(x,y){
        window.player.setPosition(window.layer.getPositionAt(x,y))
        this.startTarget = map2dx.Point(x,y)
    },
    loadStone(){
        const t = this
        t.setStone(1,1)
        t.setStone(1,0)

        t.setStone(1,2)
        t.setStone(1,3)
        t.setStone(2,4)

        t.setStone(1,5)

        t.setStone(2,5)
        t.setStone(3,5)
        t.setStone(4,5)
        t.setStone(4,6)


    }
    ,
    /**
     * @description 设置石头
     * @param x 石头的x
     * @param y 石头的y
     */
    setStone(x,y){
        const t = this
        var stone = cc.instantiate(t.stonePre)
        stone.parent = this.node
        stone.active = true
        stone.setPosition(window.layer.getPositionAt(x,y))
        t.zhangaiList.push(map2dx.Point(x,y))
    }
    // update (dt) {},
});
